package org.kjtc.controller;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kjtc.entity.WechatUser;
import org.kjtc.service.WeChartService;
import org.kjtc.weChatUtil.CommonUtil;
import org.kjtc.weChatUtil.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
public class AuthController {

    private static Logger logger = Logger.getLogger(AuthController.class);

    @Autowired
    private WeChartService weChartService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("/getAuthorizeBaseCode")
    public Object getAuthorizeBaseCode(String id, String url, String state, String uuid, Model model) {
        logger.info("微信验证：code");
        if (state == null) {
            state = "";
        }
        if (url != null) {
            state += url;
        }
        if (id != null) {
            state += "?id=" + id;
        }
        String checkResult = CommonUtil.checkUUID(uuid);
        logger.info("微信验证checkResult：" + checkResult);
        if (!StringUtils.isEmpty(checkResult)) {
            if ("Success".equals(checkResult)) {
                if (state != null && state.indexOf("?") > -1) {
                    state = state + "&uuid=" + uuid;
                } else {
                    state = state + "?uuid=" + uuid;
                }
            } else {
                model.addAttribute("error", checkResult);
                return "error/errorPage";
            }
        }
        if (CommonUtil.test_model) {
            logger.info("方法getAuthorizeBaseCode参数：id=" + id + "，url=" + url + "，state=" + state + "，uuid=" + uuid);
        }
        model.addAttribute("state", "1");
        model.addAttribute("redirectUrl", CommonUtil.wechat_authorize_url.replace("APPID", CommonUtil.appid).replace("BASEURL", CommonUtil.baseUrl_kejiatc + "getBaseOpenid").replace("STATE",  state));
        return "weChatApp/loadPage";
    }
//TODO  获取用户信息
    @RequestMapping("/getBaseOpenid")
    public Object getBaseOpenid(HttpServletRequest request, String code, String state, Model model) {
        logger.info("微信验证：BaseOpenid");
        String uuid = null;
        if (!StringUtils.isEmpty(state) && state.indexOf("uuid=") >= 0) {
            uuid = state.substring(state.indexOf("uuid=") + 5);
            String checkResult = CommonUtil.checkUUID(uuid);
            if (!"Success".equals(checkResult)) {
                model.addAttribute("error", checkResult);
                return "error/errorPage";
            }
        }
        if (StringUtils.isNotBlank(code)) {
            JSONObject jsonObject = null;
            if (request.getSession() != null && request.getSession().getAttribute(CommonUtil.SESSION_USER) != null) {
                jsonObject = new JSONObject();
                jsonObject.put("openid", request.getSession().getAttribute(CommonUtil.SESSION_USER));
            } else {
                String access_token_url = CommonUtil.wechat_access_token_url.replace("APPID", CommonUtil.appid).replace("SECRET", CommonUtil.appsecret).replace("CODE", code);
                String result = HttpClient.requestHttpGet(access_token_url);
                if(StringUtils.isNotBlank(result)) {
                    jsonObject = JSONObject.fromObject(result);
                } else {
                    logger.error("微信验证BaseOpenid失败，访问微信接口：" + access_token_url + "无返回结果，重新获取微信验证'code'");
                    return getAuthorizeBaseCode(null, null, state, null, model);
                }
            }
            if (jsonObject != null && jsonObject.has("openid")) {
                request.getSession().setAttribute(CommonUtil.SESSION_USER, jsonObject.getString("openid"));
                String openid = jsonObject.getString("openid");
                if (redisTemplate.hasKey(openid)) {
                    redisTemplate.opsForValue().set(openid, CommonUtil.date2Str(new Date(), null), 2, TimeUnit.HOURS);
                    if (uuid != null) {
                        model.addAttribute("uuid", uuid);
                        if (System.currentTimeMillis() - Long.parseLong(uuid.split("_")[0]) > 0) {
                            JSONObject json = new JSONObject();
                            json.put("openid", openid);
                            json.put("status", "1");
                            redisTemplate.opsForValue().set(uuid, json.toString(), System.currentTimeMillis() - Long.parseLong(uuid.split("_")[0]), TimeUnit.MILLISECONDS);
                            json = null;
                        }
                        uuid = null;
                        return "weChatApp/wechatLogin";
                    }
                } else {
                    redisTemplate.opsForValue().set(openid, CommonUtil.date2Str(new Date(), null), 2, TimeUnit.HOURS);
                }
                WechatUser wechatUser = new WechatUser();
                wechatUser.setWeChatID(openid);
                List<WechatUser> userlist = weChartService.searchWechatUser(wechatUser);
                wechatUser = null;
                if (userlist != null && userlist.size() > 0) {
                    if (!userlist.get(0).isEnabled()) {
                        logger.error("用户" + userlist.get(0).getWeChatNickName() + "：" + userlist.get(0).getUserName() + "未关注，跳转页面失败");
                        model.addAttribute("error", "Unsubscribe");
                        return "error/errorPage";
                    } else if (uuid != null && !userlist.get(0).isLoginEnabled()) {
                        logger.error("用户" + userlist.get(0).getWeChatNickName() + "：" + userlist.get(0).getUserName() + "无权限或未关注，跳转页面失败");
                        model.addAttribute("error", "UserNotEnabled");
                        return "error/errorPage";
                    } else {
                        if (uuid != null) {
                            model.addAttribute("uuid", uuid);
                            if (System.currentTimeMillis() - Long.parseLong(uuid.split("_")[0]) > 0) {
                                JSONObject json = new JSONObject();
                                json.put("openid", openid);
                                json.put("status", "1");
                                redisTemplate.opsForValue().set(uuid, json.toString(), System.currentTimeMillis() - Long.parseLong(uuid.split("_")[0]), TimeUnit.MILLISECONDS);
                                json = null;
                            }
                            return "weChatApp/wechatLogin";
                        } else {
                            model.addAttribute("state", "0");
                            if (StringUtils.isEmpty(state)) {
                                state = "https://www.kejiatc.cn";
                            } else {
                                if (state.indexOf("?") > -1) {
                                    state = state + "&userID=" + userlist.get(0).getUserID() + "&openID=" + userlist.get(0).getWeChatID();
                                } else {
                                    state = state + "?userID=" + userlist.get(0).getUserID() + "&openID=" + userlist.get(0).getWeChatID();
                                }
                            }
                            model.addAttribute("redirectUrl", state);
                            if (CommonUtil.test_model) {
                                logger.info("用户" + userlist.get(0).getWeChatNickName() + "：" + userlist.get(0).getUserName() + "验证成功，跳转页面:" + state);
                            }
                            return "weChatApp/loadPage";
                        }
                    }
                } else {
                    logger.error("用户openid：" + jsonObject.getString("openid") + "不存在用户无法获取用户ID，跳转信息详细页面失败");
                    model.addAttribute("error", "UserNotExist");
                    return "error/errorPage";
                }
            } else {
                logger.error("微信验证BaseOpenid失败，'openid'不存在");
                model.addAttribute("error", "OpenidNotExist");
                return "error/errorPage";
            }
        } else {
            logger.warn("微信验证'code'不存在，重新获取");
            return getAuthorizeBaseCode(null, null, state, null, model);
        }
    }
    @RequestMapping("/subscribeWeChat")
    public Object subscribeWeChat(HttpServletRequest request) {
        return "redirect:https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI0Nzc0ODgxOA==#wechat_redirect";
    }
}